package com.lemon.stock.viewmodel

import androidx.lifecycle.*
import com.lemon.stock.app.StockApplication
import com.lemon.stock.entity.Stock
import com.lemon.stock.net.SinaStock
import com.lemon.stock.util.sysStockExchange
import kotlinx.coroutines.launch

class StocksViewModel : ViewModel() {
    private val _finished = MutableLiveData<Boolean>()
    private val _stocks = MutableLiveData<List<Stock>>()
    private val _stock = MutableLiveData<Stock>()
    private val _remote = MutableLiveData<String>()

    val finished: LiveData<Boolean>
        get() = _finished
    val stocks: LiveData<List<Stock>>
        get() = _stocks
    val stock: LiveData<Stock>
        get() = _stock
    val remote: MutableLiveData<String>
        get() = _remote

    /**
     * 设置完成时重置状态标志
     */
    fun finishReset(){
        _finished.postValue(false)
    }

    /**
     * 获取关注的股票列表
     */
    fun fetchStocks(){
        viewModelScope.launch {
            val stockDao = StockApplication.getDataRoom().stockDao()
            val liStock = stockDao.followStocks()
            _stocks.postValue(liStock)
        }
    }

    /**
     * 通过股票代码获取股票
     */
    fun fetchStock(id: String){
        viewModelScope.launch {
            val stockDao = StockApplication.getDataRoom().stockDao()
            val siStock = stockDao.findById(id)
            _stock.postValue(siStock)
        }
    }

    /**
     * 从新浪接口中获取股票信息，并insert到stock表中
     */
    fun remoteStock(id: String){
        viewModelScope.launch {
            _remote.postValue("")
            val stockDao = StockApplication.getDataRoom().stockDao()
            val siStock = stockDao.findById(id)
            if(siStock == null){
                val stockQuery = sysStockExchange(id)
                var liStock:List<String> = listOf(stockQuery)
                SinaStock.send(liStock) {
                    _remote.postValue(id)
                    //println(it)
                }
            }
        }
    }

    /**
     * 获取股票的最新价格
     * 批量从新浪获取，数据为关注的股票的价格
     */
    fun remoteStocks(ids: List<String>){
        viewModelScope.launch {
            if(ids.isNotEmpty()){
                SinaStock.send(ids){
                    val stockDao = StockApplication.getDataRoom().stockDao()
                    val liStock = stockDao.followStocks()
                    _stocks.postValue(liStock)
                }
            }
        }
    }

    /**
     * 股票提示线设置
     */
    fun stockSetup(stock: Stock, buy: Float, sell: Float){
        stock.buyLine = buy
        stock.sellLine = sell
        val stockDao = StockApplication.getDataRoom().stockDao()
        stockDao.update(stock)
        _finished.postValue(true)
    }

}